package com.wt.interceptor;

import com.wt.pojo.Distributor;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * Author hiberk
 * Date 2017/6/30 19:05
 */
public class ManageInterceptor implements HandlerInterceptor {
    Logger log = Logger.getLogger(ManageInterceptor.class);
    private List<String> urls;

    public List<String> getUrls() {
        return urls;
    }

    public void setUrls(List<String> urls) {
        this.urls = urls;
    }

    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {

    }

    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
            throws Exception {

    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
        Distributor distributor = (Distributor) request.getSession().getAttribute("distributor");
        String context = request.getContextPath() + "/index";
        String uri = request.getRequestURI();
        if (-1 == uri.indexOf(context)) {
//            访问的不是首页且未登录
            if (null == distributor) {
                response.getWriter().write("<script type='text/javascript'>window.top.location.href='" + context + "'</script>");
                return false;
            }
            return true;
        } else {
//            访问的是首页且已经登陆过的时候
            if (null != distributor) {
                response.sendRedirect("/distributor/details");
                return false;
            }
        }
        return true;
    }
}
